#include "utilities.h"
#include <cmath>

int Utilities::binToDec(const QString& str)
{
    bool ok;
    if (str.mid(0, 1) == "0")
    {
        return str.toInt(&ok, 2);
    }
    return str.toLongLong(&ok, 2) - pow(2, str.length());
}

quint32 Utilities::binToUDec(const QString &input)
{
    bool ok;
    return input.toLongLong(&ok, 2);
}

QString Utilities::hexToBin(const QString &input)
{
    bool ok;
    quint32 value = input.toLongLong(&ok, 16);
    QString result;
    if(!ok)
    {
        return result;
    }
    result.setNum(value, 2);
    while(result.size() < 32)
    {
        result.prepend("0");
    }
    return result;
}

QString Utilities::binToHex(const QString &input)
{
    Q_ASSERT(input.size() == 32);
    bool ok;
    QString result;
    for(int i = 0; i < 8; i++)
    {
        QString temp = input.mid(4 * i, 4);
        int value = temp.toInt(&ok, 2);
        temp.setNum(value, 16);
        result.append(temp);
    }
    return result.prepend("X");
}

QString Utilities::decToBin(const qint64& it)
{
    QString temp;
    temp.setNum(it, 2);
    int length = temp.length();
    if (it < 0)
    {
        return temp.mid(32);
    }
    for (int i = 0; i < (32 - length); i++)
    {
        temp = "0" + temp;
    }
    return temp;
}

QString Utilities::uintToHex(quint32 value)
{
    QString result;
    result.setNum(value, 16);
    while(result.size() < 8)
    {
        result.prepend("0");
    }
    result.prepend("X");
    return result.toUpper();
}

QString Utilities::signExtend(const QString &input)
{
    Q_ASSERT(input.size() <= 32);
    QChar signBit = input.at(0);
    QString result = input;
    while(result.size() < 32)
    {
        result.prepend(signBit);
    }
    return result;
}
